/*
 * @Author: qinuoyun
 * @Date:   2021-09-25 13:44:33
 * @Last Modified by:   qinuoyun
 * @Last Modified time: 2021-09-25 15:32:52
 */
const NodeCache = require("node-cache");
const Cache = new NodeCache();
const request = require('request');

class Tools {
    /**
     * 设置缓存，按需重载
     * @param string $cachename
     * @param mixed $value
     * @param int $expired
     * @return bool
     */
    static setCache($cachename, $value, $expired = 0) {
        return Cache.set($cachename, $value, $expired);
    }

    /**
     * 获取缓存，按需重载
     * @param string $cachename
     * @return mixed
     */
    static getCache($cachename) {
        return Cache.get($cachename);
    }

    /**
     * 清除缓存，按需重载
     * @param string $cachename
     * @return bool
     */
    static removeCache($cachename) {
        return Cache.del($cachename);
    }

    /**
     * SDK日志处理方法
     * @param string $msg 日志行内容
     * @param string $type 日志级别
     */
    static log($msg, $type = 'MSG') {
        Cache.put($type + ' - ' + $msg);
    }


    /**
     * 以get方式提交请求
     * @param $url
     * @return bool|mixed
     */
    static httpGet($url) {
        return new Promise((resolve, reject) => {
            request({
                url: $url,
                method: "GET",
            }, function(error, response, body) {
                if (!error && response.statusCode == 200) {
                    resolve(body)
                } else {
                    reject(error);
                }
            });
        })
    }

    /**
     * 以post方式提交请求
     * @param string $url
     * @param array|string $data
     * @return bool|mixed
     */
    static httpPost($url, $data) {
        return new Promise((resolve, reject) => {
            request({
                url: $url,
                method: "POST",
                json: true,
                headers: {
                    "content-type": "application/json",
                },
                body: JSON.stringify($data)
            }, function(error, response, body) {
                if (!error && response.statusCode == 200) {
                    resolve(body)
                } else {
                    reject(error);
                }
            });
        })
    }
}

module.exports = Tools;